package filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.User;
import java.io.IOException;

@WebFilter("/*") // 拦截所有请求
public class LoginFilter implements Filter {

    // 不需要拦截的路径
    private static final String[] EXCLUDE_PATHS = {
            "/login.jsp", "/LoginServlet", "/css/", "/js/", "/error/", "/favicon.ico"
    };

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String path = req.getRequestURI().replace(req.getContextPath(), "");

        // 检查是否需要排除拦截
        boolean exclude = false;
        for (String excludePath : EXCLUDE_PATHS) {
            if (path.startsWith(excludePath)) {
                exclude = true;
                break;
            }
        }

        if (exclude) {
            chain.doFilter(request, response);
            return;
        }

        // 检查Session中是否有登录用户
        User user = (User) req.getSession().getAttribute("loginUser");
        if (user == null) {
            // 未登录，重定向到登录页
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void destroy() {}
}
